<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\job;

use app\BaseController;
use app\wework\controller\Base;
use think\facade\Db;
use app\wework\model\BaseModel;
use app\wework\model\QyWechatApi;
use think\facade\Log;
use think\queue\Job;


/**
    * 个人Sop类
*/
class CustomerSopJob extends BaseController{
    public function index(){
        $config_list = Db::table('kt_wework_config')->where(["customer_status"=>1])->column("wid");
        if(!$config_list) return success("操作失败");
        foreach ($config_list as $user) {
           $this->sop($user);
        }
        return success("操作成功");
    }

    public function sop($wid){
        $list = Db::table("kt_wework_customer_sop")
                ->where(["wid"=>$wid,"status"=>1,"scene_type"=>1])
                ->whereTime("start_date",">=",date("Y-m-d"))
                ->json(["staffid","filter_tag"])
                ->filter(function($data){
                    $data["rule_data"] = Db::table('kt_wework_customer_sop_rule')->where("sop_id","=",$data["id"])->where("status","=",1)->json(["send_content","send_timing_data"])->select()->toArray();
                    return $data;
                })
                ->select()
                ->toArray();
        if(!count($list))return success("操作成功");
        foreach ($list as $value){
            foreach ($value["rule_data"] as $rule_data){
                if($rule_data["send_type"] == 1){
                    if($rule_data["send_timing_data"]["type"] == "minute"){
                        $time = strtotime(date("Y-m-d H:i"))-60*$rule_data["send_timing_data"]["number"];
                    }else if($rule_data["send_timing_data"]["type"] == "hour"){
                        $time = strtotime(date("Y-m-d H:i"))-3600*$rule_data["send_timing_data"]["number"];
                    }else if($rule_data["send_timing_data"]["type"] == "day"){
                        $time = strtotime(date("Y-m-d"))-(3600*24)*$rule_data["send_timing_data"]["number"];
                        if(date("H:i") < $rule_data["send_timing_data"]["time"])continue;
                    }
                    $status = Db::table("kt_wework_customer_sop_status")->where(["pid"=>$rule_data["id"],"wid"=>$wid])->json(["external_userid"])->find();
                    $external_userid = Db::table("kt_wework_customer")
                        ->where("staff_id","in",$value["staffid"])
                        ->whereBetweenTime("createtime",$time,$time+60);
                    if($status){
                        $external_userid = $external_userid->whereNotIn('external_userid',$status["external_userid"]);
                    }
                    if($value["filter_tag"]){
                        foreach ($value["filter_tag"] as $filter_tag){
                            $external_userid = $external_userid->whereNotLike('tags','%'.$filter_tag.'%');
                        }
                    }
                    $external_userid = $external_userid->column("external_userid");
                    if(!$external_userid)continue;
                    $data["pid"] = $rule_data["id"];
                    $data["ctime"] = time();
                    $data["wid"] = $wid;
                    $data["external_userid"] = json_encode($external_userid,320);
                    if($status){
                        $data["external_userid"] = json_encode(array_merge($status["external_userid"],$external_userid),320);
                        Db::table("kt_wework_customer_sop_status")->where(["pid"=>$rule_data["id"],"wid"=>$wid])->save($data);
                    }
                    if(!$status)Db::table("kt_wework_customer_sop_status")->insertGetId($data);
                }else{
                    if($rule_data["send_starttime_type"] == 2){
                        if($rule_data["send_starttime"] < date("Y-m-d"))continue;
                    }
                    if($rule_data["send_endtime_type"] == 2){
                        if($rule_data["send_endtime_date"] < date("Y-m-d")){
                            Db::table('kt_wework_customer_sop_rule')->where("id","=",$rule_data["id"])->save(["status"=>2]);
                            continue;
                        }
                    }
                    $status = Db::table("kt_wework_customer_sop_status")->where(["pid"=>$rule_data["id"],"wid"=>$wid])->max("ctime");
                    $time = 0;
                    if($rule_data["send_frequency_type"] == "minute" && $status){
                        $time = $status+60*$rule_data["send_frequency"];
                    }else if($rule_data["send_frequency_type"] == "hour" && $status){
                        $time = $status+3600*$rule_data["send_frequency"];
                    }else if($rule_data["send_frequency_type"] == "day" && $status){
                        $time = $status+(3600*24)*$rule_data["send_frequency"];
                    }
                    if($time > time())continue;
                    $external_userid = Db::table("kt_wework_customer")
                        ->where("staff_id","in",$value["staffid"]);
                    if($value["filter_tag"]){
                        foreach ($value["filter_tag"] as $filter_tag){
                            $external_userid = $external_userid->whereNotLike('tags','%'.$filter_tag.'%');
                        }
                    }
                    $external_userid = $external_userid->column("external_userid");
                    if(!$external_userid)continue;
                    $data["pid"] = $rule_data["id"];
                    $data["ctime"] = time();
                    $data["wid"] = $wid;
                    if($status)Db::table("kt_wework_customer_sop_status")->where(["pid"=>$rule_data["id"],"wid"=>$wid])->save($data);
                    if(!$status)Db::table("kt_wework_customer_sop_status")->insertGetId($data);
                }
                if($rule_data["trigger_form"] == 1){
                    $welcome_data = $this->welcome($rule_data["send_content"],$wid);
                    $msg = ["content"=>$rule_data["send_content"]["text"]];
                    $res = QyWechatApi::addMsgTemplate($wid,$external_userid,"",$msg,$welcome_data);
                    if($res["errcode"] != 0)continue; 
                }else{
                    $data["pid"] = $rule_data["id"];
                    $save["wid"] = $wid;
                    $save["external_userid"] = json_encode($external_userid,320);
                    $id = Db::table("kt_wework_customer_sop_status")->insertGetId($save);
                    $userid = Db::table("kt_wework_staff")->where(["id"=>$value["staffid"]])->column("userid");
                    $userid = implode("|",$userid);
                    $send = "管理员创建了推送任务，提醒你给".count($external_userid)."个客户发送应用消息"
                    $send_res = QyWechatApi::send_textcard($userid,$wid,"个人SOP提醒",$send,$this->req->domain().'/wework/h5.CustomerSopJob/index.html?id='.$id);
                }
            }
        }
        return success("操作成功");
    }
    
    public function welcome($otherData,$wid){
        $data = [];
        foreach ($otherData["content"] as $other) {
            switch ($other['type']) {
                case '1':
                    $data[] = [
                        'msgtype'=>'image',
                        'image'=>[
                            'media_id' => QyWechatApi::mediaUpload($wid,$other['url'],'image')['media_id'],
                        ]
                    ];
                    break;
                case '2':
                    $data[] = [
                        'msgtype'=>'link',
                        'link'=>[
                            'title' => $other['link_title'],
                            'picurl' => $other['link_picurl'],
                            'desc' => $other['link_desc'],
                            'url' => $other['link_url'],
                        ]
                    ];
                    break;
                case '3':
                    $data[] = [
                        'msgtype'=>'miniprogram',
                        'miniprogram'=>[
                            'title' => $other['miniprogram_title'],
                            'pic_media_id' => QyWechatApi::mediaUpload($wid,$other['miniprogram_imgurl'],'image')['media_id'],
                            'appid' => $other['miniprogram_appid'],
                            'page' => $other['miniprogram_page'],
                        ]
                    ];
                    break;
            }
        }
        return $data;
    }
}